import {
	defineStore
} from 'pinia'
import {
	login
} from '../api'
import {
	setAuthorization,
	removeAuthorization
} from '../utils/auth.js'

export const useUserStore = defineStore({
	id: 'user',
	persist: true,
	state: () => {
		return {
			isLogin: false,
			userInfo: {
				userNickname: '',
				userName: '',
				avatar: '',
			}
		}
	},
	actions: {
		loginFun(loginData) {
			return login(loginData).then((res) => {
				setAuthorization(res.data.token)
				this.userInfo.userNickname = res.data.userNickname
				this.userInfo.avatar = res.data.avatar
				this.userInfo.userName = res.data.userName
				// 跳转首页
				uni.switchTab({
					url: '/pages/index/index'
				})
			})
		},
		logout() {
			removeAuthorization()
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	},
	// 配置持久化
	persist: {
		// 调整为兼容多端的API
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value) // [!code warning]
			},
			getItem(key) {
				return uni.getStorageSync(key) // [!code warning]
			},
		},
	}
})